package cn.gene.timeyan.ams.webapi.service.impl;

import cn.gene.timeyan.ams.service.IAdvertiseService;
import cn.gene.timeyan.ams.webapi.mapper.AdvertiseMapper;
import cn.gene.timeyan.ams.webapi.mapper.ImgMapper;
import cn.gene.timeyan.ams.webapi.utils.AdvertiseCacheUtils;
import cn.gene.timeyan.ams.webapi.utils.UploadUtils;
import cn.gene.timeyan.common.exception.TimeyanServiceException;
import cn.gene.timeyan.common.restful.JsonPage;
import cn.gene.timeyan.common.restful.ResponseCode;
import cn.gene.timeyan.pojo.admin.dto.AdvertiseAddDTO;
import cn.gene.timeyan.pojo.admin.dto.AdvertiseUpdateDTO;
import cn.gene.timeyan.pojo.admin.model.Advertise;
import cn.gene.timeyan.pojo.admin.vo.AdvertiseVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 广告    服务实现类*
 *
 * @author LWG
 * @date 2022/7/21 17:42
 * @since 1.0.0@gene.cn
 */
@Service
@Slf4j
public class AdvertiseServiceImpl implements IAdvertiseService {
    //@Value:找到配置文件中的值读取出来并赋值给dirPath变量
    @Value("${dirPath}")
    private String dirPath;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 自动装配持久层mapper
     */
    private final AdvertiseMapper advertiseMapper;
    private final ImgMapper imgMapper;

    public AdvertiseServiceImpl(AdvertiseMapper advertiseMapper, ImgMapper imgMapper) {
        this.advertiseMapper = advertiseMapper;
        this.imgMapper = imgMapper;
    }

    /**
     * 增加广告
     * @param advertiseAddDTO
     */
    @Override
    public void addAD(AdvertiseAddDTO advertiseAddDTO) {
        log.info("添加广告的方法...");
        //实例化广告的实体类Advertise
        Advertise advertise = new Advertise();
        //将AdvertiseAddDTO的同名属性赋值给Advertise
        BeanUtils.copyProperties(advertiseAddDTO,advertise);
        LocalDateTime now = LocalDateTime.now();
        advertise.setCreateTime(now);
        advertise.setUpdateTime(now);
        log.info("执行插入广告...");
        int row = advertiseMapper.insertAD(advertise);
        if (row != 1){
            throw new TimeyanServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"服务器繁忙!请稍后重试..");
        }
        List<String> imgUrls = advertiseAddDTO.getImgUrl();
        if (imgUrls == null){
            throw new TimeyanServiceException(ResponseCode.BAD_REQUEST,"请至少上传一张图片!");
        }
        log.info("执行插入广告图片...");
        imgMapper.insertADImg(advertise.getAdId(),imgUrls);
    }

    @Override
    public String handlePicture(MultipartFile picFile) {
        log.info("开始处理图片...");
        String imgUrl = UploadUtils.upload(dirPath, picFile);
        return imgUrl;
    }

    /**
     * 根据adId删除广告
     * @param adId
     */
    @Override
    public void deleteAD(Long adId) {
        log.info("删除广告的方法,adId为{}",adId);
        int row = advertiseMapper.deleteADByAdId(adId);
        if (row != 1){
            throw new TimeyanServiceException(ResponseCode.BAD_REQUEST,"该广告不存在!");
        }
        log.info("该广告删除成功!");
        log.info("开始执行删除图片...");
        imgMapper.deleteADImgByAdId(adId);
    }

    @Override
    public void removeADImg(String name) {
        log.info("将图片从本地删除");
        int isSuccess = UploadUtils.remove(dirPath, name);
        if (isSuccess != 1){
            throw new TimeyanServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"服务器繁忙!");
        }
    }

    @Override
    public void updateAD(AdvertiseUpdateDTO advertiseUpdateDTO) {
        log.info("开始执行修改广告的方法...");
        Advertise advertise = new Advertise();
        BeanUtils.copyProperties(advertiseUpdateDTO,advertise);
        LocalDateTime now = LocalDateTime.now();
        advertise.setCreateTime(now);
        advertise.setUpdateTime(now);
        log.info("调用广告的持久层...");
        advertiseMapper.updateADByAdId(advertise);
        List<String> imgUrl = advertiseUpdateDTO.getImgUrl();
        if (imgUrl != null){
            imgMapper.deleteADImgByAdId(advertise.getAdId());
            imgMapper.insertADImg(advertise.getAdId(),imgUrl);
        }
        log.info("修改完成!");
    }

    @Override
    public JsonPage<AdvertiseVO> selectAdvertise(Integer page, Integer pageSize) {
        log.info("开始执行查询广告的方法...");
        //判断redis中是否有该数据
        String advertiseKey = AdvertiseCacheUtils.getAdvertiseVOKey();
        if (redisTemplate.hasKey(advertiseKey)){
            log.info("redis中有该数据...");
            List<AdvertiseVO> advertiseVOS = (List<AdvertiseVO>) redisTemplate.boundValueOps(advertiseKey).get();
            return JsonPage.restPage(new PageInfo<>(advertiseVOS));
        }
        // 分页查询秒杀表中spu信息
        log.info("redis中没有该数据...");
        PageHelper.startPage(page,pageSize);
        List<AdvertiseVO> advertiseVOS = advertiseMapper.selectAdvertise();
        redisTemplate.boundValueOps(advertiseKey).set(advertiseVOS,60*60*24*1000+
                        RandomUtils.nextInt(1000*60*60*2),
                TimeUnit.MILLISECONDS);
        System.out.println("------------------------------");
        return JsonPage.restPage(new PageInfo<>(advertiseVOS));
    }
}
